// serial_service.c
#include "../inc/serial_service.h"
#include "definitions.h"
#include "../inc/cli_core.h"

#define RX_BUFFER_SIZE 256
static uint8_t rxBuffer[RX_BUFFER_SIZE];
static size_t  rxWriteIndex = 0;
static size_t  rxReadIndex  = 0;

void Serial_Init(void)
{
    USART_SERIAL_SETUP serialSetup = {
        .baudRate  = 115200,
        .parity    = USART_PARITY_NONE,
        .dataWidth = USART_DATA_8_BIT,
        .stopBits  = USART_STOP_1_BIT,

    };

    SERCOM0_USART_SerialSetup(&serialSetup, 0);
    SERCOM0_USART_Enable();
}

void Serial_Printf(const char *format, ...)
{
    char    buffer[256];
    va_list args;
    va_start(args, format);
    vsnprintf(buffer, sizeof(buffer), format, args);
    va_end(args);
    SERCOM0_USART_Write((uint8_t *)buffer, strlen(buffer));
}

void Serial_Task(void)
{
    size_t bytesRead = SERCOM0_USART_ReadCountGet();
    if (bytesRead > 0)
    {
        SERCOM0_USART_Read(&rxBuffer[rxWriteIndex], bytesRead);
        rxWriteIndex = (rxWriteIndex + bytesRead) % RX_BUFFER_SIZE;

        // 解析命令
        uint8_t temp[256] = {0};
        size_t  len       = 0;

        while ((rxReadIndex != rxWriteIndex) && len < sizeof(temp) - 1)
        {
            temp[len++] = rxBuffer[rxReadIndex];
            rxReadIndex = (rxReadIndex + 1) % RX_BUFFER_SIZE;
        }

        parseSerialCommand(temp, len);
    }
}